/**
 * Copyright  2025, Hai Yue Xing He  ZHAO LIMIN
 *
 * @author          ZHAO LIMIN
 * @version         1.0.1
 * @since           2025-04
 * Stack.ts         堆栈
 * 堆栈是一种线性数据结构，它遵循后进先出（LIFO）原则。
 * 这意味着最后添加的元素将首先被移除。
 * 堆栈通常用于管理函数调用、表达式求值和内存管理等任务。
 */
interface StackNode<T> {
  value: T
  next: StackNode<T> | null
}
export class Stack<T> {
  private top: StackNode<T> | null = null
  private size: number = 0

  push(element: T): void {
    const node: StackNode<T> = {
      value: element,
      next: this.top,
    }
    this.top = node
    this.size++
  }

  pop(): T | undefined {
    if (this.isEmpty()) return undefined
    const value = this.top!.value
    this.top = this.top!.next
    this.size--
    return value
  }

  peek(): T | undefined {
    return this.top?.value
  }

  isEmpty(): boolean {
    return this.size === 0
  }

  getSize(): number {
    return this.size
  }

  clear(): void {
    this.top = null
    this.size = 0
  }
}
